package com.ls.fw.token.handler.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import com.ls.fw.token.annotation.RequireToken;
import com.ls.fw.token.handler.HttpTokenHandler;
import com.ls.fw.token.support.Token;
import com.ls.fw.token.support.TokenRepository;


/**
 * token處理器
 * 
 * @author lisheng
 * @date 2015年12月24日 下午6:36:31
 * @version V1.0
 */
public class DefaultTokenHandlerImpl implements HttpTokenHandler{

	private TokenRepository	 tokenRepository;

	@Override
	public boolean checkToken(HttpServletRequest request, String token) {
		String requestToken = this.decodeToken(token, request);
		String sessionToken = this.getToken(request, token, false);
		 if (StringUtils.isNotBlank(sessionToken)
				 && sessionToken.equals(requestToken)) {
			 return true;
		 }
		 return false;
	}

	@Override
	public String createToken(HttpServletRequest request,
			HttpServletResponse response, String token) {
		Token token1 = tokenRepository.generateToken(request);
		tokenRepository.saveToken(token1, request, response);
		return token1.getToken();
	}

	@Override
	public void removeToken(HttpServletRequest request,
			HttpServletResponse response, String token) {
		tokenRepository.removeToken(null, request, response);
	}

	@Override
	public String getToken(HttpServletRequest request, String token,boolean createIFNoExist) {
		Token token1 = tokenRepository.loadToken(request, createIFNoExist);
		return token1!=null?token1.getToken():null;
	}

	@Override
	public void success(HttpServletRequest request,
			HttpServletResponse response, String token, RequireToken annotation) {
		if(annotation.onceLife()){
			this.removeToken(request, response, token);
		}
		if(annotation.generateNew()){
			this.removeToken(request, response, token);
			response.setHeader(this.tokenRepository.getHeaderName(), this.createToken(request, response, token));
		}else{
			if(!annotation.onceLife()){
				response.setHeader(this.tokenRepository.getHeaderName(), token);
			}
		}
	}

	@Override
	public void fail(HttpServletRequest request, HttpServletResponse response,
			String token) throws IOException {
		
	}

	@Override
	public String decodeToken(String baseToken, HttpServletRequest request) {
	     return baseToken;
	}


	@Override
	public String getKey(HttpServletRequest request, String token) {
		return request.getSession().getId();
	}

	public TokenRepository getTokenRepository() {
		return this.tokenRepository;
	}

	public void setTokenRepository(TokenRepository tokenRepository) {
		this.tokenRepository = tokenRepository;
	}
}
